const Sequelize = require("sequelize");
const bcrypt = require("bcryptjs");
const sequelize = require("../config/database");
const Comment = require("../models/Comment");
const Spot = require("../models/Spot");
const User = sequelize.define(
  "user",
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    username: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true,
      validate: {
        notEmpty: true,
        isAlphanumeric: true,
        len: [1, 20],
      },
    },
    email: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true,
      validate: {
        notEmpty: true,
        isEmail: true,
      },
    },
    password: {
      type: Sequelize.STRING,
      allowNull: false,
      validate: {
        notEmpty: true,
        len: [1, 100],
      },
    },
  },
  {
    freezeTableName: true,
  }
);

User.beforeCreate(async (user) => {
  const salt = await bcrypt.genSaltSync();
  user.password = await bcrypt.hashSync(user.password, salt);
});

User.prototype.isValidPassword = async function (password) {
  const compare = await bcrypt.compareSync(password, this.password);
  return compare;
};
// User.hasMany(Spot,{as:});
// Spot.hasOne(User);
// User.hasMany(Comment);
// Comment.hasOne(User);
// User.belongsToMany(Spot, { through: "Favorite" });
// Spot.belongsToMany(User, { through: "Favorite" });
// User.associate = (models) => {
//   User.hasMany(models.Spot, {
//     foreignKey: {
//       name: "spotId",
//       allowNull: false,
//     },
//     as: "spots",
//   });
//   return User;
// };
// User.hasMany(Spot);
// User.hasMany(Comment, { through: Spot });
module.exports = User;
